import {useState,useEffect} from 'react'
import {Card,Button,Modal} from 'antd'
import {useNavigate} from 'react-router-dom'
import api from '../api'
import { scanQRCodePay } from '../helpers'

interface IProduct {
  id:string
  name:string
  cover:string
  price:number
}


function Products() {
  const [products,setProducts]  = useState([])
  const navatige = useNavigate()
  const fetchProducts = ()=>{
    api.get('/products').then(response=>{
      setProducts(response.data)
    })
  }
  
  useEffect(fetchProducts,[])

  async function handleBuy(product:IProduct){
    try{
        // 调用支付接口
        const response = await api.get(`/payment/native/${product.id}`)
        // 拿到code_url,orderNo
        const {code_url,orderNo} = response.data
        console.log(code_url,orderNo)
        scanQRCodePay({orderNo,code_url,callback:()=>navatige(`/orders`)})
    }catch(error){
      console.log(`下单错误:${error}`)
      Modal.error({
        title:'错误',
        content: "无法下单"
      })
    }
  }

  return (
    <>
      {products.map((product:IProduct)=>(
        <Card
        key={product.id}
        style={{
          width:240,
          float:'left',
          margin:"16px",
        }}
        hoverable
        cover={<img alt={product.name} src={product.cover}></img>}
        actions={[<Button type='primary' onClick={()=>handleBuy(product)}>立即购买</Button>]}
        >
          <Card.Meta title={product.name} description={`价格:${(product.price / 100).toFixed(2)}`}></Card.Meta>
        </Card>
      ))}
    </>
  )
}


export default Products